package org.grow.authfilter.service;

import org.grow.authfilter.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-8-4
 */

@Service
public class SwaggerAuth {
    @Value("${swaggerName:anonymous007}")
    private String swaggerName;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserInfo supplyAuth(){
        String sql1 = "select * from UserInfo where username = ?";

//                默认swagger 没有任何角色信息，那么只有当url没有加入权限系统时候，才能进行访问
//        如果加入了权限系统，swagger还想要继续访问，只能通过直接修改swagger对应的角色信息修改
        List<UserInfo> users = jdbcTemplate.query(sql1, new BeanPropertyRowMapper<>(UserInfo.class), swaggerName);
        if (users.size() == 0){
            UserInfo user = new UserInfo();
            user.setUsername(swaggerName);
            user.setPassword("888888");
            user.setIsEnable(true);
            user.setNickname("匿名swagger");
            user.setUserId(-1);
            user.setAuthorities(Collections.emptyList());
            return user;
        }else {
            System.out.println("有匿名用户信息");

            UserInfo userDetails = (UserInfo) userInfoService.loadUserByUsername(swaggerName);
            return userDetails;
        }
    }
}
